package com.naiterui.ehp.bs.im.api;

import com.alibaba.fastjson.JSON;
import com.naiterui.ehp.bp.bo.im.DoctorsMedicalRecordBO;
import com.naiterui.ehp.bp.bo.im.FollowUpImMsgBO;
import com.naiterui.ehp.bp.bo.im.MessageSendResultBO;
import com.naiterui.ehp.bp.bo.im.MsgSendParamBO;
import com.naiterui.ehp.bp.bo.im.PatientMsgSendBO;
import com.naiterui.ehp.bp.bo.im.PatientMsgSendParamBO;
import com.naiterui.ehp.bp.bo.im.RecomSendDTO;
import com.naiterui.ehp.bp.bo.im.SessionDetailBO;
import com.naiterui.ehp.bp.bo.im.SessionParamBO;
import com.naiterui.ehp.bp.bo.im.UserCommonParams;
import com.naiterui.ehp.bp.bo.im.UserSessionStatusBO;
import com.naiterui.ehp.bp.constants.SwaggerTag;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.support.exception.PublicService;
import com.naiterui.ehp.bp.support.exception.ResponseVO;
import com.naiterui.ehp.bp.support.utils.JsonMapper;
import com.naiterui.ehp.bs.im.dto.MessageSendResultDTO;
import com.naiterui.ehp.bs.im.dto.RecomRemindDTO;
import com.naiterui.ehp.bs.im.exception.ExceptionCodes;
import com.naiterui.ehp.bs.im.exception.NaiteruiIMException;
import com.naiterui.ehp.bs.im.service.IMessageService;
import com.naiterui.ehp.bs.im.service.INaiteruiIMService;
import com.naiterui.ehp.bs.im.service.ISessionService;
import com.naiterui.ehp.bs.im.task.SessionTask;
import com.naiterui.ehp.bs.im.vo.ConsultInitVO;
import com.naiterui.ehp.bs.im.vo.PageVO;
import com.naiterui.ehp.bs.im.vo.SessionVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 服务间调用Api
 */
@Api(tags = {SwaggerTag.INNER_API + SwaggerTag.IM})
@RestController
@AllArgsConstructor
public class InnerApi {

    /**
     * 日至输出类
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(InnerApi.class);

    private final INaiteruiIMService naiteruiIMService;
    private final SessionTask sessionTask;
    private final IMessageService messageService;
    private final ISessionService sessionService;

    /**
     * 会话列表
     */
    @RequestMapping(value = "/inner/session/list")
    public ResponseVO<PageVO<SessionDetailBO>> sessionList(@RequestBody SessionParamBO sessionParam) throws Exception {
        PageVO<SessionDetailBO> pageVO = this.naiteruiIMService.sessionPageList(sessionParam);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS, pageVO);
    }

    /**
     * 群发消息
     */
    @RequestMapping(value = "/chat/sendMultipleMessage", method = RequestMethod.POST)
    public void sendMultiplepMessage(String message, String batchId, String toIds, String header) throws BusinessException {
        LOGGER.info("chat sendMultipleMessage info ; batchId:{},message:{},toId:{},header:{}", batchId, message, toIds, header);
        this.naiteruiIMService.sendMultipleMessage(message, toIds);
    }

    /**
     * 自动结束会话数据更新
     */
    @RequestMapping(value = "/sessionTask/generateData")
    public void genSessionData(Long duration) {
        // Default 任务周期:10min，执行有效期:9min
        if (null == duration) {
            duration = (long) (9 * 60 * 1000);
        }
        this.sessionTask.doWork(duration);
    }

    /**
     * 更新付款状态
     */
    @RequestMapping(value = "/session/paid")
    public void sessionPaid(String sessionId) throws Exception {
        this.naiteruiIMService.sessionPaid(sessionId);
    }

    /**
     * 患者支付完成后创建付费会话
     *
     * @return
     */
    @RequestMapping("/consult/session/init")
    public SessionVO paidConsult(ConsultInitVO consultInitVO) throws BusinessException {

        if (null == consultInitVO || consultInitVO.getPatientId() == null || consultInitVO.getDoctorId() == null
                || consultInitVO.getPayAmount() == null || StringUtils.isEmpty(consultInitVO.getDoctorName())
                || StringUtils.isEmpty(consultInitVO.getPatientName())) {
            throw new BusinessException(ExceptionCodes.PARAM_ERROR);
        }
        LOGGER.info("患者支付完成后创建付费会话,params:{}", consultInitVO.toString());
        return this.naiteruiIMService.createConsultSessionAndNotice(consultInitVO);
    }

    /**
     * 推荐服务发送推荐消息
     */
    @RequestMapping(value = "/inner/sendRecommend", method = RequestMethod.POST)
    public ResponseVO<MessageSendResultDTO> sendRecommend(@RequestBody @ApiParam(type = "body") RecomSendDTO recomSend) throws BusinessException {
        LOGGER.info("推荐服务发送推荐消息,参数:{}", recomSend.toString());
        MessageSendResultDTO responseVO = this.messageService.sendRecommend(recomSend);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS, responseVO);
    }

    /**
     * 推送推荐审核结果消息
     */
    @RequestMapping(value = "/inner/remindRecommend", method = RequestMethod.POST)
    public ResponseVO<Void> remindRecommend(@RequestBody @ApiParam RecomRemindDTO recomRemind) throws BusinessException {
        LOGGER.info("推送推荐审核结果消息,参数:{}", recomRemind.toString());
        this.messageService.sendRecommend(recomRemind);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);
    }


    /**
     * 根据医生id,患者id查询当前是否有会话
     */
    @RequestMapping("inner/session/isalive")
    public ResponseVO<List<UserSessionStatusBO>> sessionStatus(@RequestBody UserCommonParams userCommonParams) throws NaiteruiIMException {
        LOGGER.info("请求参数:{}", userCommonParams.toString());
        if (userCommonParams.getDoctorIds() == null || userCommonParams.getDoctorIds().size() == 0 || userCommonParams.getPatientId() == null) {
            throw new NaiteruiIMException(ExceptionCodes.PARAM_ERROR);
        }
        List<UserSessionStatusBO> statusList = this.sessionService.isSessionAlive(userCommonParams.getDoctorIds(), userCommonParams.getPatientId());
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS, statusList);
    }

    /**
     * 患者发送病历给医生
     */
    @Deprecated
    @RequestMapping("inner/patientsMedicalRecord/send")
    public ResponseVO<Integer> sendPatientsMedicalRecord(Long doctorId, Long patientId, String caseId) throws BusinessException {
        LOGGER.info("患者向医生发送病历,doctorId：{},patientId:{},caseId:{}", doctorId, patientId, caseId);
        if (doctorId == null || patientId == null || caseId == null) {
            throw new NaiteruiIMException(ExceptionCodes.PARAM_ERROR);
        }
        Integer sendResult = this.messageService.sendPatientsMedicalRecord(doctorId, patientId, caseId, null);
        return PublicService.returnResponseVO(sendResult);
    }

    /**
     * 提醒患者填写病历
     */
    @Deprecated
    @RequestMapping("inner/patientsMedicalRecordFill/send")
    public ResponseVO<Void> sendPatientsMedicalRecordFillReminder(Long doctorId, Long patientId) throws NaiteruiIMException {
        LOGGER.info("提醒患者填写病历,doctorId：{},patientId:{}", doctorId, patientId);
        if (doctorId == null || patientId == null) {
            throw new NaiteruiIMException(ExceptionCodes.PARAM_ERROR);
        }
        this.messageService.sendPatientsMedicalRecordFillReminder(doctorId, patientId);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);
    }

    /**
     * 医生给患者发送填写的病历
     */
    @RequestMapping("inner/doctorsMedicalRecord/send")
    public ResponseVO<MessageSendResultBO> sendDoctorsMedicalRecord(@RequestBody DoctorsMedicalRecordBO doctorsMedicalRecordBO)
            throws NaiteruiIMException {
        LOGGER.info("医生给患者发送填写的病历:{}", doctorsMedicalRecordBO.toString());
        if (doctorsMedicalRecordBO.getDoctorId() == null || doctorsMedicalRecordBO.getPatientId() == null) {
            throw new NaiteruiIMException(ExceptionCodes.PARAM_ERROR);
        }
        doctorsMedicalRecordBO.setSend(true);
        MessageSendResultBO resultBo = this.messageService.sendDoctorsMedicalRecord(doctorsMedicalRecordBO);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS, resultBo);
    }

    /**
     * 内部服务结束会话
     */
    @RequestMapping("inner/session/finish")
    public ResponseVO<Void> finishSession(Long doctorId, Long patientId, Integer triggerSource) throws NaiteruiIMException {
        LOGGER.info("服务内部结束会话接口 参数,doctorId:{},patientId:{},triggerSource:{}", doctorId, patientId, triggerSource);
        // 验证字段
        if (doctorId == null || patientId == null || triggerSource == null) {
            throw new NaiteruiIMException(ExceptionCodes.PARAM_ERROR);
        }
        this.sessionService.finishSessionByDeletePatient(doctorId, patientId, triggerSource);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);
    }

    /**
     * 患者微信入口-消息发送-4java
     */
    @PostMapping("inner/message/send")
    public ResponseVO<PatientMsgSendBO> patientMsgSend(@RequestBody PatientMsgSendParamBO msgSendParamBO) throws BusinessException {
        LOGGER.info("患者微信入口-消息发送-4java : body={}", JSON.toJSONString(msgSendParamBO));
        PatientMsgSendBO patientMsgSendBO = this.messageService.sendPatientMsg(msgSendParamBO);
        return PublicService.returnResponseVO(patientMsgSendBO);
    }

    /**
     * 会话结束-服务评价-消息发送
     */
    @PostMapping("inner/serviceEvaluation/send")
    public ResponseVO<Void> sendServiceEvaluation(@RequestBody String message) throws BusinessException {
        LOGGER.info("会话结束-服务评价-消息发送 : body={}", JSON.toJSONString(message));
        this.messageService.sendServiceEvaluation(message);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);
    }

    /**
     * 向患者发送系统消息
     */
    @PostMapping("inner/patient/sys/message/send")
    public ResponseVO<Void> sendPatientSysMessage(@RequestBody PatientMsgSendParamBO msgSendParamBO) throws BusinessException {
        LOGGER.info("向患者发送系统消息 : body={}", JSON.toJSONString(msgSendParamBO));
        this.messageService.sendPatientSysMessage(msgSendParamBO);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);
    }

    /**
     * 发送系统消息
     */
    @PostMapping("inner/sys/message/send")
    public ResponseVO<Void> sendSysMessage(@RequestBody MsgSendParamBO msgSendParamBO) throws BusinessException {
        LOGGER.info("发送系统消息 : body={}", JSON.toJSONString(msgSendParamBO));
        this.naiteruiIMService.sendSysMessage(msgSendParamBO);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);
    }

    @GetMapping("inner/session/detail/list")
    @ApiOperation("会话集合")
    public ResponseVO<List<SessionDetailBO>> sessionDetail(String sessionIds) {
        List<SessionDetailBO> sessionDetailList = sessionService.sessionDetailList(sessionIds);
        return PublicService.returnResponseVO(sessionDetailList);
    }

    /**
     * 随访卡片
     * 
     * @param followUpImMsg
     * @return
     * @throws BusinessException
     */
    @PostMapping("/inner/followup")
    public ResponseVO<Void> sendFollowUp(@RequestBody FollowUpImMsgBO followUpImMsg) throws BusinessException {
        LOGGER.info("推送随访卡片消息,参数:{}", JsonMapper.toJson(followUpImMsg));
        this.messageService.sendFollowUpMessage(followUpImMsg);
        return PublicService.returnResponseVO(ExceptionCodes.SUCCESS);
    }
}
